# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from typing import List


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        # 固定一个数字，双指针另外两个数，找三个数字的和 与 目标值 差的绝对值最小 的和
        nums.sort()
        n = len(nums)
        if n < 3:
            return
        res = nums[0] + nums[1] + nums[2]
        for i in range(n - 2):
            # 去重
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            l = i + 1
            r = n - 1
            while l < r:
                s = nums[i] + nums[l] + nums[r]
                if s == target:
                    return s
                if abs(s - target) < abs(res - target):
                    res = s
                if s < target:
                    l += 1
                if s > target:
                    r -= 1
        return res
    # Press the green button in the gutter to run the script.


if __name__ == '__main__':
    nums = [-1, 2, 1, -4]
    target = 1
    solution = Solution()
    print(solution.threeSumClosest(nums, target))

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
